package yxy.game.pm2.command.mail;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.MailMessage;
import yxy.game.pm2.module.mail.MailBean;
import yxy.game.pm2.module.mail.MailHandle;

/** 邮件 邮件打开 */
@MessageType(proto = Command.MailRead, classtype = MailMessage.MailReadRequest.class)
public class CMD_MailRead extends Command<MailMessage.MailReadRequest> {

	@Override
	public void execute(MessageSource messageSource, MailMessage.MailReadRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();

		MailMessage.MailReadResponse.Builder response = MailMessage.MailReadResponse.newBuilder();

		MailBean mailBean = MailBean.get(playerCode, code);
		if (mailBean == null || mailBean.expired()) {
			send(messageSource, response, Result.MailExpired);//邮件已过期
			return;
		}

		mailBean.setReaded(true);
		MailBean.set(playerCode, mailBean);

		response.setMail(new MailHandle().packMail(playerCode, mailBean));

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, MailMessage.MailReadResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}